package reserve

import (
    "time"
	"dhfshop/controllers/base"
	"dhfshop/models/reserve"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type TimeslotController struct {
	base.BaseController
}

func (this *TimeslotController) List() {
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	l, cnt, err := reserve.GetAllTimeslots(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount   int64           `json:"total_count"`
		Timeslot []*reserve.Timeslot `json:"timeslots"`
	}{TotalCount: cnt, Timeslot: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *TimeslotController) Update() {
	var v reserve.Timeslot
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.TimeslotId, "timeslot_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	if v.SchemaId > 0 {
	    v.Schema, _= reserve.GetSchemaById(v.SchemaId)
	}
	if v.PeriodId > 0 {
	    v.Period, _= reserve.GetPeriodById(v.PeriodId)
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"timeslot_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := reserve.UpdateTimeslotById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		TimeslotId  int64     `json:"timeslot_id"`
		Modified    time.Time `json:"modified"`
	}{TimeslotId: v.TimeslotId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *TimeslotController) Delete() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v := struct {
		PartnerId   int64     `form:"-"  valid:"Required"`
		PeriodId    int64   `form:"period_id"`
		TimeslotId  int64   `form:"timeslot_id"`
	}{PartnerId: partnerId}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	err := reserve.DeleteTimeslotByMultiCond(v.PartnerId,v.PeriodId,v.TimeslotId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		PeriodId  int64     `json:"period_id"`
		Modified  time.Time `json:"modified"`
	}{PeriodId: v.PeriodId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

